﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Silvermoon.Controls;
using OutlookHub.Styles;
using Silvermoon.Images;
using OutlookHub.Images;
using OutlookHub.Controls;
using MAPIdotnet;
using OutlookHub.Models;
using OutlookHub.Utils;
using Silvermoon.UI;
using Silvermoon.Animations;
using Silvermoon.Navigation;
using Silvermoon.Controls.Forms;
using OutlookHub.Controllers;
using Silvermoon.Windows;


namespace OutlookHub.Pages
{
    public class EMailsPage : Page
    {
        private Toolbar tb;
        private bool isInitialized = false;
        private ProgressingControl progressing;
        private EMailContext controller;
        private TabControl tabs;
        private TabPage allTab, unreadTab, flaggedTab, urgentTabs;
        private ListView allListView, unreadListView, flaggedListView, urgentListView;
        private ListViewController<EMailItem, Message> allController, unreadController, flaggedController, urgentController;
        private bool areCheckboxesVisible = false;
        private ContextMenu itemMenu;

        public EMailsPage()
            : base()
        {
            KeepAlive = true;
            InitializePage();
        }


        protected override void Dispose(bool dispose)
        {
            DisposeObject(itemMenu);
            base.Dispose(dispose);
        }

        public bool AreCheckBoxesVisible
        {
            get { return areCheckboxesVisible; }
            set
            {
                if (areCheckboxesVisible != value)
                {
                    areCheckboxesVisible = value;
                    OnCheckboxesVisibilityChanged();
                }
            }
        }

        private void OnCheckboxesVisibilityChanged()
        {
            if (areCheckboxesVisible) SetEditToolbarButtons(); else SetDefaultToolbarButtons();
            allListView.UpdateItems();
            unreadListView.UpdateItems();
        }

        private void InitializePage()
        {
            Title = "EMAILS: " + EMailContext.Context.CurrentFolder.Name;
            Styles = StylePool.EMails;
            SetTransition(350, TransitionMask.RotateLeftIn, TransitionMask.RotateLeftIn);

            tabs = new TabControl { Margin = new Margin(0, 0, 0, 12), TabHeight = 90 };
            tabs.PageChanging += new EventHandler(tabs_PageChanging);

            allListView = new ListView { Multiselect = true };
            unreadListView = new ListView { Multiselect = true };
            flaggedListView = new ListView { Multiselect = true };
            urgentListView = new ListView { Multiselect = true };

            itemMenu = new ContextMenu();
            itemMenu.AddItem("mark as flagged");
            itemMenu.AddItem("mark as completed");
            itemMenu.AddItem("delete");

            allController = CreateController(allListView);
            unreadController = CreateController(unreadListView);
            flaggedController = CreateController(flaggedListView);
            urgentController = CreateController(urgentListView);

            allTab = new TabPage("all", allListView);
            unreadTab = new TabPage("unread", unreadListView);
            flaggedTab = new TabPage("flagged", flaggedListView);
            urgentTabs = new TabPage("urgent", urgentListView);
            tabs.SetPages(allTab, unreadTab, flaggedTab, urgentTabs);
            tabs.SelectedPage = allTab;
            Controls.Add(tabs);

            progressing = new ProgressingControl { Margin = new Margin(0, null, 0, 0), Visible = true, TextColor = PhoneColors.Black, Height = 12 };
            Controls.Add(progressing);


            tb = new Toolbar();
            SetDefaultToolbarButtons();
            Toolbar = tb;
        }

        void tabs_PageChanging(object sender, EventArgs e)
        {
            AreCheckBoxesVisible = false;
        }

        private void SetDefaultToolbarButtons()
        {
            tb.Buttons.Clear();
            tb.MenuItems.Clear();
            tb.AddButton(SysImages.Back, Page.BackCommand);
            tb.AddButton(SysImages.Add).Tap += new EventHandler<TapEventArgs>(OnAdd);
            tb.AddButton(ImagePool.Folder).Tap += new EventHandler<TapEventArgs>(FolderTap);
            tb.AddButton(ImagePool.SortOrder).Tap += new EventHandler<TapEventArgs>(OnSelection);
            tb.AddButton(ImagePool.Sync).Tap+=new EventHandler<TapEventArgs>(SyncEMails);
        }


        void SyncEMails(object sender, EventArgs e)
        {
            string store = EMailContext.Context.CurrentStore.Name;
            MapiSync.Sync(store);
        }

        private void SetEditToolbarButtons()
        {
            tb.Buttons.Clear();
            tb.AddButton(SysImages.RecycleBin);
            tb.AddButton("").Tap += new EventHandler<TapEventArgs>(EMailsPage_Tap);
            tb.AddMenuItem("mask as read");
            tb.AddMenuItem("mask as unread");
            tb.AddMenuItem("set flag");
            tb.AddMenuItem("complete");
            tb.AddMenuItem("clear flag");
        }

        void EMailsPage_Tap(object sender, TapEventArgs e)
        {
            AreCheckBoxesVisible = false;
        }



        void OnAdd(object sender, TapEventArgs e)
        {
            NotImplemented.Show();
        }

        void OnSelection(object sender, TapEventArgs e)
        {
            AreCheckBoxesVisible = true;
        }

        void FolderTap(object sender, TapEventArgs e)
        {
            EMailFoldersPage page = new EMailFoldersPage();
            KeepAlive = false;
            this.NavigateTo(page);
        }

        private ListViewController<EMailItem, Message> CreateController(ListView listView)
        {
            var controller = new ListViewController<EMailItem, Message>(listView);
            controller.ItemHeight = 140;
            controller.InitializeItem += new EventHandler<ItemControlGeneratorEventArgs<EMailItem>>(controller_InitializeItem);
            controller.UpdateItem += new EventHandler<ItemControlGeneratorEventArgs<EMailItem>>(controller_UpdateItem);
            return controller;

        }

        void controller_UpdateItem(object sender, ItemControlGeneratorEventArgs<EMailItem> e)
        {
            e.Item.IsCheckBoxVisible = AreCheckBoxesVisible;
        }

        void controller_InitializeItem(object sender, ItemControlGeneratorEventArgs<EMailItem> e)
        {
            e.Item.Tap += new EventHandler<TapEventArgs>(OnItemTap);
            e.Item.Updated += new EventHandler(Item_Updated);
            e.Item.ContextMenu = itemMenu;
        }

        void Item_Updated(object sender, EventArgs e)
        {
            EMailItem item = sender as EMailItem;
            item.IsCheckBoxVisible = AreCheckBoxesVisible;
        }

        void OnItemTap(object sender, TapEventArgs e)
        {
            AreCheckBoxesVisible = false;
            Item item = sender as Item;
            Message msg = item.DataValue as Message;
            if (msg != null)
            {
                EMailDetailsPage page = new EMailDetailsPage(msg);
                Screen.Renderer.BackgroundColor = PhoneColors.White;
                this.NavigateTo(page);
            }
        }

        protected override void OnShown()
        {
            base.OnShown();
            if (!isInitialized)
            {
                isInitialized = true;
                LoadData();
                BlendData();
            }
        }

        private void BlendData()
        {
            isInitialized = true;
            IntTransition transition = new IntTransition { Duration = 1300, From = 0, To = 255 };
            OpacityProperty.Animate(allListView, transition);
            OpacityProperty.Animate(unreadListView, transition);
            OpacityProperty.Animate(flaggedListView, transition);
            OpacityProperty.Animate(urgentListView, transition);
        }

        private void LoadData()
        {
            controller = EMailContext.Context;
            var ds = controller.MailMessages.OrderByDescending(m => m.DeliveryDate).ToArray();
            allController.DataSource = ds;
            unreadController.DataSource = ds.Where(m => (m.Flags & EMessageFlags.MSGFLAG_READ) == 0);
            flaggedController.DataSource = ds.Where(m => (m.Flagged != FollowUpStatus.None));
            urgentController.DataSource = ds.Where(m => (m.Priority == Priority.High));
        }

        private class Bag
        {
            public int TabIndex;
        }

        protected override void OnBack(HandledEventArgs e)
        {
            Screen.Renderer.BackgroundColor = PhoneColors.Black;
            KeepAlive = false;
            base.OnBack(e);
        }

        protected override void OnHome(HandledEventArgs e)
        {
            Screen.Renderer.BackgroundColor = PhoneColors.Black;
            KeepAlive = false;
            base.OnHome(e);
        }

        public override object OnSaveViewState()
        {
            return new Bag { TabIndex = tabs.SelectedIndex };
        }

        public override void OnLoadViewState(object viewState)
        {
            Bag bag = viewState as Bag;
            if (bag != null)
            {
                tabs.SelectedIndex = bag.TabIndex;
            }
        }

        protected override void OnCommand(CommandEventArgs args)
        {
            if (args.Command == OutlookCommands.DisableEMailItemSelectMode)
            {
                AreCheckBoxesVisible = false;
                args.Handled = true;
            }
            base.OnCommand(args);
        }
    }
}
